<?php
// +----------------------------------------------------------------------
// |     【DealMain】Controller 控制器
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\admin\controller\deal;

use think\facade\Db;
use think\facade\Request;
use app\common\service\DealMain as S;
use app\common\service\DealInfo as INFO_S;
use app\common\model\DealMain as M;
use app\common\service\BillMain as BILL_S;
use app\common\model\DealInfo as INFO_M;
use app\common\model\CustomerMain as CUS;
use app\common\model\ClothMain as CLOTH;
use app\common\model\ClothColor as COLOR;
use app\common\model\ExpressMain as EXP_M;
use app\common\model\SystemConfig as CONFIG;

class Main extends  \app\admin\controller\Base
{
    protected $middleware = ['AdminCheck','AdminPermission'];
	private $maxlist=15;					//默认最高行数

	//初始化
	public function initialize(){
		parent::initialize();
		
		$this->assign('controller_title','订单管理');
	}

    // 列表
    public function index(){
        if (Request::isAjax()) {
			$keyword = I("keyword",'');
            return $this->getJson(M::getList([[$keyword==''?'uuid':'DealMain.uuid','=',$this->uuid]]));
        }
		
		$status = I("status",'');
		$cusid = I("cusid",'');
		$year=I('get.year','');
		$month=I('get.month','');
		$day=I('get.day','');
		$cost=I('get.cost',0);
		
		$old_year=M::where(['uuid'=>$this->uuid])->order('create_time asc')->value('create_time');
		$old_year=$old_year!=''?date('Y',$old_year):date('Y');
		
        return $this->fetch('',[
			'old_year'=>$old_year,
			'status'=>$status,
			'cusid'=>$cusid,
			'year'=>$year,
			'month'=>$month,
			'day'=>$day,
			'cost'=>$cost,
		]);
    }

    // 添加
    public function add(){
        if (Request::isAjax()) {
			$data=array_merge(Request::post(),['uuid'=>$this->uuid]);
            $result=S::goAdd($data);
			//判断是否添加成功
			if(array_key_exists('code',$result)){
				return $this->getJson($result);
			}else{
				INFO_S::write_info($result['info'],$result['id'],$this->uuid);
					
				self::upcustomer($result['model']['cusid'],$this->uuid);	//更新用户销售情况
				self::up_volume($result['id'],$this->uuid);					//更新匹数
				BILL_S::up_bill($result['id'],$this->uuid);		//更新收支
				
				return $this->getJson();
			}
        }
        return $this->fetch('edit',[
			'action_up'=>false,
			'options'=>config_cache_file('options'),
			'courier'=>EXP_M::listData(['uuid'=>$this->uuid],['sort'=>"asc","id"=>"asc"],1,200),
			'maxlist'=>I('get.maxlist',$this->maxlist,'intval'),
		]);
    }

    // 编辑
    public function edit($id){
        if (Request::isAjax()) {
			$result=S::goEdit(Request::post(),['id'=>$id,'uuid'=>$this->uuid]);
			//判断是否修改成功
			if(array_key_exists('code',$result)){
				return $this->getJson($result);
			}else{
				INFO_S::write_info($result['info'],$id,$this->uuid);
				
				self::upcustomer($result['model']['cusid'],$this->uuid);	//更新用户销售情况
				self::up_volume($id,$this->uuid);							//更新匹数
				BILL_S::up_bill($id,$this->uuid);				//更新收支
				
				return $this->getJson();
			}
        }
		$maxlist=I('get.maxlist',0,'intval');
		$model=M::info(['uuid'=>$this->uuid,'id'=>$id]);
		if($model!=''){
			$Tinfo=INFO_M::listData($id,[],'id asc');
			if($maxlist==0){
				if(count($Tinfo)>=$this->maxlist){
					$maxlist=count($Tinfo)+5;
				}else{
					$maxlist=$this->maxlist;
				}
			}
			return $this->fetch('',[
				'action_up'=>true,
				'model' => $model,
				'Tinfo'=>$Tinfo,
				'maxlist'=>$maxlist,
				'options'=>config_cache_file('options'),
				'courier'=>EXP_M::listData(['uuid'=>$this->uuid],['sort'=>"asc","id"=>"asc"],1,200),
			]);
		}else{
			$this->getJson(1202);	
		}
    }
	
	//统计客户的交易额
	public static function upcustomer($cusid,$uuid=0){
		if(!is_array($cusid)) $cusid=[$cusid];		//支持多个客户统计
		foreach ($cusid as $id) {
			$total=M::where(['cusid'=>$id,'uuid'=>$uuid,'status'=>1])->sum('total');
			$count=M::where(['cusid'=>$id,'uuid'=>$uuid,'status'=>1])->count();
			CUS::where(['id'=>$id,'uuid'=>$uuid])->save(['dealtotal'=>$total,'dealcount'=>$count]);
		}
	}
	
	//*更新统计匹数
	private static function up_volume($id,$uuid){
		$volume=INFO_M::where(['did'=>$id,'uuid'=>$uuid])->sum('roll');
		M::where(['id'=>$id,'uuid'=>$uuid])->save(['volume'=>$volume]);
	}

    // 状态
    public function status($id){
        return $this->getJson(S::goStatus(Request::post(),['id'=>$id,'uuid'=>$this->uuid]));
    }

    // 删除
    public function remove($id){
        return $this->getJson(S::goRemove($id,$this->uuid));
    }

    // 批量删除
    public function batchRemove(){
        return $this->getJson(S::goBatchRemove(Request::post('ids'),$this->uuid));
    }

    // 回收站
    public function recycle(){
        if (Request::isAjax()) {
            return $this->getJson(S::goRecycle([['uuid','=',$this->uuid]]));
        }
        return $this->fetch();
    }
	
    // 设置某个值
    public function setValue(){
        if (Request::isAjax()) {
            return $this->getJson(S::setFieldValue(Request::post(),['id'=>I('post.id'),'uuid'=>$this->uuid]));
        }
        return $this->fetch();
    }
	
	// 打印明细
	public function printing(){
		$mid=I('get.mid',0);
		$qrshow=I('get.qr',1);
		$px=I('get.px');
		
		$print=CONFIG::get('info.print');
		if(empty($print)) $this->error('请先配置【打印设置】参数！');
		
		//排序方式
		switch ($px) {
			case 1:						//先排产品，再排色号
				$sort='number asc,color asc';
				break;
			case 2:						//先排产品
				$sort='number asc';
				break;
			case 3:						//先排产品，再数量
				$sort='number asc,count asc';
				break;
			default:
				$sort='id asc';
				break;
		}
		$where=' and uuid='.$this->uuid;

		//单独订单打印
		if($mid==0){
			$id=I('id');
			$number=I('number');
			if($number!='') $where=' and number='.$number;
			
			$T=M::info($id,$where);
			if($T!=''){
				$Tinfo=INFO_M::listData($id,['uuid'=>$this->uuid],$sort,false);
			}else{
				$this->error('订单不存在！');
			}
		}else{			//合并打印
			$did=explode('|',$mid);
			$Tab=M::listData([['id','in',$did],['uuid','=',$this->uuid]],'',false);
			if($Tab!=''){
				$Customer=CUS::info(['id'=>$Tab[0]['cusid'],'uuid'=>$this->uuid]);
				$Tinfo=INFO_M::listData($did,[['uuid','=',$this->uuid]],$sort);
				$total=0;$count=0;$coupon=0;$freight=0;
				foreach ($Tab as $v) {
					$total+=$v['total'];
					$count+=$v['count'];
					$coupon+=$v['coupon'];
					$freight+=$v['freight'];
				}
				$Tab[0]['total']=$total;
				$Tab[0]['count']=$count;
				$Tab[0]['freight']=$freight;
				$Tab[0]['coupon']=$coupon;
				$Tab[0]['company']=$Customer['company'];
				$Tab[0]['name']=$Customer['name'];
				$T=$Tab[0];
			}
		}
		
		if(isMobile()){
			$tpl_name='printwap';
		}else{
			$tpl_name='print';
		}
		
		//二维码提示文字 和 二维码内容
		$qr_type = intval($print['deal_qrcode_type']??0);
		$qrcode_url='';
		if($qr_type===0){					//不显示二维码
			$qrshow = 0;
		}else if($qr_type===2){			//扫呗支付
			//密匙用于校验
			$key=\core\Encode::lcsw_notify_key($T['id']);
			$print['deal_qrcode_content']=U('Saobei/pay',['n'=>$T['number'],'k'=>$key,'ssid'=>$this->uuid],true,'api');
			$print['deal_qrcode_tips']='微信支付 / 支付宝';
		}
		
		// 生成二维码图片URL
		if($print['deal_qrcode_content']!=''){
			$qrcode_url=U('Result/rqcode',['str'=>base64_encode($print['deal_qrcode_content']),'d'=>0,'pass'=>64],true,'api');
		}
		
		//备注信息
		if($print['deal_remark']==''){
			$print['deal_remark']="注：请您核对本单后验收，<b>大货重量均为毛重（含纸管空差）。</b>如发现质量问题，<b>请勿剪裁！</b>于收货后三天内与本司联系，协商解决，若经裁剪或自行其他工序概不退换。<b>货物如无质量问题，一经松布、裁剪或自行其他工序概不退换</b>；散剪米样一律不支持退换。品名不代表成分。";
		}
		
		$print_data=M::dealPrintData($T,$Tinfo,$print);

		return $this->fetch($tpl_name,[
			'T'=>$T,
			'print'=>$print,
			'qrcode_url'=>$qrcode_url,
			'qrshow'=>$qrshow,							//是否显示二维码
			'print_data'=>json_encode($print_data),
			'Tinfo'=>$Tinfo,
		]);
	}
	
	// 订单明细
	public function info(){
		$px=I('get.px');
		
		//排序方式
		switch ($px) {
			case 1:						//先排产品，再排色号
				$sort='number asc,color asc';
				break;
			case 2:						//先排产品
				$sort='number asc';
				break;
			case 3:						//先排产品，再数量
				$sort='number asc,count asc';
				break;
			default:
				$sort='s.id asc';
				break;
		}
		$where=' and uuid='.$this->uuid;
	
		$id=I('id');
		$number=I('number');
		if($number!='') $where=' and number='.$number;
		
		$T=M::info($id,$where);

		if($T!=''){
			$Tinfo=INFO_M::listData($id,['i.uuid'=>$this->uuid],$sort,true);
		}else{
			$this->error('订单不存在！');
		}
		
		return $this->fetch('info',[
			'T'=>$T,
			'Tinfo'=>$Tinfo,
		]);
	}
	
	//搜索历史订单
	public function history(){
		if (Request::isAjax()) {
		    return $this->getJson(INFO_M::history(['DealInfo.uuid'=>$this->uuid]));
		}
		
		return $this->fetch('',[
			'cusid'=>I('cusid',0),
		]);
	}
	
	//大货标签打印
	public function label(){
		$id=I('id');
		$print=CONFIG::get('info.print');
		if(empty($print)) $this->error('请先配置【打印设置】参数！');
		
		$count=INFO_M::where(['uuid'=>$this->uuid])->count();
		if($count>0){
			$Tinfo=INFO_M::listData($id,['unit'=>'KG','i.uuid'=>$this->uuid],'id asc',true);

			$qr_type=intval($print['label_qrcode_type'])??0;
			$qr_content=$print['label_qrcode_content']??'';
			$qrshow=1;						//显示二维码
			if($qr_type===0){				//无需显示二维码
				$qrshow=0;
			}else if($qr_type===1){			//用户自定义二维码内容
			}else if($qr_type===2){			//小程序二维码		
				$qr_content=get_api_host(true).'/wxqrcode/'.$this->uuid.'/cloth?id=';
			}
			
			//根据是否显示二维码判断标题宽度
			$title_width=$qr_type===0?80:56;
			//计算字体大小
			if($print['label_title']!=''){
				$fontsize=($title_width-2)/mb_strlen($print['label_title'],'utf-8');
			}else{
				$fontsize=0;
			}
			
			
			$label_tips="签收请先验货，如果质量问题，请勿裁剪或者加工！并在三天内联系本司协商处理，否则概不受理！品名不代表成分！";
			
			return $this->fetch('',[
				'qr_type'	=>	$qr_type,
				'qrcode'	=>	base64_encode($qr_content),
				'title'		=>	$print['label_title']??'',
				'tips'		=>	$print['label_tips']=='' ? $label_tips : $print['label_tips'],
				'print_name' => $print['printer_name3'],
				'title_width'=>	$title_width,
				'fontsize'	=>	$fontsize,
				'count'		=>	0,
				'Tinfo'		=>	$Tinfo,
			]);
		}else{
			$this->error('订单不存在！');
		}
	}
	
	//更新订单颜色参数
	public function upDealColor(){
		if (Request::isAjax()) {
			$sql="select a.id,b.name,b.val,b.gray,b.onumber,b.ocolorid from ".env('database.prefix')."deal_info as a left join ".env('database.prefix')."cloth_color as b on a.number=b.number and a.color=b.colorid where (a.colorname='' or a.onumber='') and b.id>0 and a.uuid=".$this->uuid;
			$res=Db::query($sql);
			if(count($res)>0){
				$i=0;
				foreach($res as $val){
					$sql="update ".env('database.prefix')."deal_info set colorname='".$val['name']."',colorval='".$val['val']."',gray=".$val['gray'].",onumber='".$val['onumber']."',ocolorid=".$val['ocolorid']." where id=".$val['id'].' and uuid='.$this->uuid;
					//$sql.';<br>';
					if(Db::execute($sql)){
						$i++;
					}
				}
				return $this->getJson(['msg'=>'更新'.$i.'条信息！']);
			}else{
				return $this->getJson(['code'=>201,'msg'=>'暂无内容更新!']);
			}
		}else{
			return $this->getJson(404);
		}
	}
	
	//动态加载产品列表数据
	public function cloth(){
		if(Request::isAjax()){
			$data=F($this->uuid.'/colth_list');
			if($data==''){
				$Cloth=CLOTH::field('id,number,title,price1,price2,price3,price4,markup')->where(['uuid'=>$this->uuid])->select()->toArray();
				$Cloth=set_key($Cloth,'number');
				$data=$Cloth;
				F($this->uuid.'/colth_list',serialize($Cloth));
			}else{
				$data=unserialize($data);
			}
			return json($data);
		}else{
			$this->error('参数有误！');
		}
	}
	
	//动态加载产品列表数据
	public function color(){
		if(Request::isAjax()){
			$id=I('post.id',0);
			$colorid=I('post.color',0);
			$color=COLOR::where('pid='.$id.' and colorid='.$colorid.' and uuid='.$this->uuid)->field('id,name,val,gray,rose,onumber,ocolorid')->find();
			return json($color);
		}else{
			$this->error('参数有误！');
		}
	}
}
